package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"net/http"
	"path/filepath"
)

const endpoint = "117.27.231.169:9000"
const accessKeyID = "ebWNX8Kf32zaiPk3FHDx"
const secretAccessKey = "cHKJkS5Jql5MTliNoJDtSBEpqQqf7j6Pc23cMalX"
const bucketName = "lbb"

func Upload(c *gin.Context) {

	file, err := c.FormFile("video")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数获取失败"})
		return
	}
	if file.Size > 10*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "视频过大"})
		return
	}
	m := map[string]bool{
		".mp4": true,
		".png": true,
	}
	ext := filepath.Ext(file.Filename)
	if !m[ext] {
		c.JSON(http.StatusBadRequest, gin.H{"error": "格式不正确"})
		return
	}
	open, err := file.Open()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "视频打开失败"})
		return
	}
	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})
	if err != nil {
		log.Fatalln(err)
	}
	objectName := file.Filename

	_, err = minioClient.PutObject(c, bucketName, objectName, open, file.Size, minio.PutObjectOptions{
		ContentType: "",
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "视频上传失败"})
		return
	}
	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, objectName)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "url": url})

}
